<script setup>
import { ref } from 'vue';
import { uniFetch } from '../../api/uni-fetch';
import { useUserStore } from "/store/user.js"
// import customTabbar from '@/components/customTabbar/customTabbar.vue';
import { onShareAppMessage, onLoad, onHide, onShow } from '@dcloudio/uni-app'

const pendingId = ref('');
// 非tabbar页面直接option获取id
onShow((options) => {
	const classifyId = uni.getStorageSync('classifyId');
  if (classifyId) {
    const incomingId = classifyId;
    if (classifyList.value.length > 0) {
      handleIncomingId(incomingId);
    } else {
      pendingId.value = incomingId;
    }
  }
})

onHide(() => {
	uni.removeStorageSync('classifyId');
})

onShareAppMessage(() => {
	const openid = uni.getStorageSync("userLoginCode").openid || uni.getStorageSync("userLoginCode").user.openid
	return {
		title: '华靓甄选-分类',
		path: '/pages/classify/classify?invite_token=' + openid
	}
})

const store = useUserStore()
// 搜索框事件
const searchValue = ref('')

async function search() {
	uni.navigateTo({
		url: '/pages/GoodsList/GoodsList?search=' + searchValue.value,
	})
}

// 已售随机数     已售假数据
function getOrCreateSoldCount(item) {
  // 从缓存获取
  const cachedCount = uni.getStorageSync(`sold_${item.id}`)
  if (cachedCount) {
		// 首页不增加操作
		item.soldCount = cachedCount
  } else {
    // 首次生成96-400之间的随机数
    item.soldCount = Math.floor(Math.random() * (400 - 96 + 1)) + 96
		// 更新缓存
		uni.setStorageSync(`sold_${item.id}`, item.soldCount)
  }
}

function clear() {
	searchValue.value = ''
}

const classifyIndex = ref(0)

function chooseClassify(index, id) {
	classifyIndex.value = index
	if (id) {
		page.value = 1
		resetKey.value = 1
    noMore.value = false
    loading.value = false
		goodsList.value = []
		getGoodsList(id)
	}
}

// 打开购物车弹框
const popup = ref(null)

function addTocart(item) {
	popup.value.openPop(item); // 触发子组件的事件
}

// 跳转详情
function goodsDetail(info) {
	uni.navigateTo({
		url: '/pages/ProductDetails/ProductDetails?goodsId='+info
	})
}

// 分类列表
const classifyList = ref([])
async function getClassity() {
	const res = await uniFetch.post('/category/list', { app_id: uni.appId })
	classifyList.value = res.data
	if (classifyList.value.length) {
    if (pendingId.value) {
      handleIncomingId(pendingId.value);
      pendingId.value = '';
    } else {
      getGoodsList(classifyList.value[0].id)
    }
	}
}

// 添加处理传入id的函数
function handleIncomingId(id) {
  const index = classifyList.value.findIndex(item => item.id === id);
  if (index !== -1) {
    chooseClassify(index, id);
  }
}

// 获取分类的商品列表
const goodsList = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const noMore = ref(false)
const resetKey = ref(1)
async function getGoodsList(categoryId) {
	if (loading.value || noMore.value) return
  loading.value = true
	
  const res = await uniFetch.post('/product/list', { 
    app_id: uni.appId, 
    cate_id: categoryId, 
    page: page.value, 
    pageSize: pageSize.value 
  })
	// 已售假数据
	if (res?.data?.list && res.data.list.length > 0) {
		res.data.list.forEach(item => {
			getOrCreateSoldCount(item)
		})
	}
	// 结束
	res.data.list.forEach(item => {
    item.id = item.id + '_' + resetKey.value
  })
  goodsList.value = [...goodsList.value, ...res.data.list]
  
  total.value = res.data.total * resetKey.value
	// console.log(total.value, 'total');
	
  noMore.value = goodsList.value.length >= total.value
  loading.value = false
}

function onScrollToLower() {
  if (classifyList.value.length && !noMore.value) {
		page.value++
    getGoodsList(classifyList.value[classifyIndex.value].id)
  }
	if (noMore.value) {
		resetKey.value++
		page.value = 1
		noMore.value = false
		getGoodsList(classifyList.value[classifyIndex.value].id)
	}
}

getClassity()
</script>

<template>
	<view class="container">
		<!-- 搜索框 -->
		<view class="search-wrapper">
			<uni-search-bar placeholder="请输入商品名" @confirm="search" v-model="searchValue" @clear="clear">
			</uni-search-bar>

		</view>
		<!-- 二级分类 -->
		<view class="secondary">

			<view class="cate-content">
				<!-- 左侧 一级分类 -->
				<scroll-view class="cate-left" :scroll-y="true" :style="{ height: `90vh` }">
					<text class="type-nav " @click="chooseClassify(index, item.id)"
						:class="{ selected: classifyIndex === index }" v-for="(item, index) in classifyList"
						:key="item.id">{{ item.name }}</text>
				</scroll-view>

				<!-- 右侧 二级分类 -->
				<scroll-view class="cate-right" :scroll-y="true" :style="{ height: `90vh` }" @scrolltolower="onScrollToLower">

					<view class="cate-two-box">

						<view class="goods-card-box" v-for="item in goodsList" :key="item.id" @click="goodsDetail(item.id)">

							<view class="goods-item-img">
								<image :src="item.banner_image" mode="aspectFit"></image>
							</view>
							<view class="goods-item-title">
								{{ item.title }}
							</view>
							<view class="goods-item-buy">
								<view class="goods-item-price" v-if="store.memberInfo.is_member">
									￥{{ item.member_price }}
								</view>
								<view class="goods-item-price" v-else>
									￥{{ item.price }}
								</view>
								<view class="goods-item-price-old">
									<text class="price">
										￥{{ item.old_price }}
									</text> <text class="sold">
										<!-- 已售假数据 -->
										<!-- 已售{{ item.buyer }} -->
										已售{{ item.soldCount }}
									</text>
								</view>

								<!-- 购物车 -->
								<view class="add-to-cart" @click.stop="addTocart(item)">
									<view class="icon">
										<uni-icons custom-prefix="iconfont" type="icon-gouwuche" color="#fff"
											size="16"></uni-icons>
									</view>

								</view>
							</view>

						</view>

					</view>
					<view class="empty" v-if="total === 0">
						暂无商品~
					</view>
					<view class="loading-text" v-if="loading">
						加载中...
					</view>
					<view class="loading-text" v-if="noMore && goodsList.length > 0">
						没有更多了
					</view>
					<view class="safe-area"></view>
				</scroll-view>
			</view>
		</view>
		<!-- 加入购物册 -->
		<PopupSku @openPop="addTocart(item)" ref="popup"></PopupSku>
		<!-- <customTabbar></customTabbar> -->
	</view>
</template>


<style>
page {
	background: #fff;
}
</style>
<style lang="scss">
@import "@/static/iconfont/iconfont.css";
@import "/uni.scss";
.loading-text {
  text-align: center;
  padding: 20rpx;
  color: #999;
}
.safe-area {
  height: calc(env(safe-area-inset-bottom) + 100rpx);
  background: #f8f8f8;
}
// 分类内容
.cate-content {
	display: flex;
	z-index: 1;
	background: #fff;
	// padding-top: 96rpx;
}

// 一级分类
.cate-left {
	height: 100%;
	display: flex;
	flex-direction: column;
	width: 230rpx;
	background: #f8f8f8;
	color: #222;
}


// 二级分类
.cate-right {
	overflow: hidden;
	background-color: #f5f5f5;

	.empty {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 90%;
		color: #666666;
	}


	.cate-two-box {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		width: 550rpx;
		padding: 0 0 15rpx 0;
		margin: 0 auto;

		.goods-card-box {
			margin-top: 15rpx;
			width: 270rpx;
			background-color: #fff;
			border-radius: 10rpx;
			overflow: hidden;

			.goods-item-img {
				display: flex;
				justify-content: center;
				height: 275rpx;
				width: 275rpx;
				overflow: hidden;
				margin: 0 auto;

				image {
					height: 100%;
					width: 100%;
				}
			}

			.goods-item-title {
				width: 80%;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				margin-top: 15rpx;
				color: #101010;
				font-size: 28rpx;
				line-height: 35rpx;
				padding: 0 8rpx;
			}

			.goods-item-buy {
				position: relative;
				padding: 0 8rpx 10rpx;

				.goods-item-price {
					font-size: 32rpx;
					color: darken($color: $custom-theme-red, $amount: 15%);
					line-height: 40rpx;
				}

				.goods-item-price-old {
					font-size: 18rpx;

					.price {
						text-decoration: line-through;
						color: #c0b8b5;
					}

					.sold {
						color: lighten($color: $custom-theme-red, $amount: 5%);
						font-size: 23rpx;
					}
				}

				.add-to-cart {
					position: absolute;
					bottom: 15rpx;
					right: 18rpx;
					display: flex;
					flex-direction: column;
					align-items: center;

					.icon {
						margin-bottom: 5rpx;
						background-color: #a60b00;
						width: 50rpx;
						height: 50rpx;
						border-radius: 25rpx;
						text-align: center;
						line-height: 55rpx;
					}
				}
			}
		}
	}

}

// 左侧一级分类
.type-nav {
	position: relative;
	height: 80rpx;
	z-index: 10;
	display: block;
	font-size: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;

	&.selected {
		height: 90rpx;
		background: #fff;
		color: #3bae43;
		border-right: none;
		font-size: 32 rpx;
		font-weight: 700;
	}
}


.search-wrapper {
	// background: #045ca7;
	padding: 0rpx 13rpx;
	border-bottom: 2rpx solid #a9a9a9;
}
</style>